/*
 * Copyright 2012 yura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.opu.pcm.ui.client.actions;

import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.LinkedHashMap;
import java.util.List;
import org.opu.pc.services.beans.AbstractBean;
import org.opu.pc.ui.client.MainView;
import org.opu.pc.ui.util.Options;
import org.opu.pcm.services.beans.UserBean;
import org.opu.pcm.services.beans.UserBean.SecurityGroup;

/**
 *
 * @author yura
 */
public class EditUserUsersSettings extends AddUserUsersSettings
		implements PropertyChangeListener {
    
    protected UserBean currentUser;

    public EditUserUsersSettings(String acionLabels) {
        super(acionLabels);
    }

    @Override
    public void setMainView(MainView mainView) {
        super.setMainView(mainView);
        mainView.addChangeListener(this);
    }

    @Override
    public void action(ActionEvent e) throws Exception {
        if (fillCurrentUser()) {
            return;
        }

        super.action(e);
    }

    @Override
    public String getName() {
        return "EditUser";
    }

    @Override
    public void doOkAction(UserBean user) {
        user.setId(currentUser.getId());
        currentUser = null;
        userService.updateUser(user);
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if (MainView.SELECTED_BEANS.equals(evt.getPropertyName())){
			List newValue = (List) evt.getNewValue();
			setEnabled(newValue != null && newValue.size() == 1);
		}
    }

    @Override
    protected List<SecurityGroup> getPrivilegesList() {
        return currentUser.getSecurityGroups();
    }

	@Override
	protected void initProp(LinkedHashMap<String, Object> properties) {
		properties.put("user.name", currentUser.getName());
		properties.put("user.password", "");
		properties.put("user.email", currentUser.getEmail());
	}

    protected boolean fillCurrentUser() {
        List<? extends AbstractBean> selected = mainView.getSelectedBeans();
        if (selected == null || selected.size() != 1) {
            Options.error(getSafety(getName() + ".err1", "You need to select "
                    + "one user"));
            return true;
        }
        currentUser = (UserBean) selected.get(0);
        return false;
    }
    
}
